---
title: experimental_useAssistant
---

import { OptionTable } from '@/components/table';
import { FrameworkTabs, Tab } from '@/components/framework-tabs';

# experimental_useAssistant

## `experimental_useAssistant(options: UseAssistantOptions): UseAssistantHelpers` [#experimental_useAssistant]

`useAssistant` is a utility designed to handle the UI state of interacting with an OpenAI-compatible assistant API.
This tool is useful when you need to integrate assistant capabilities into your application,
with the UI updated automatically as information is received from the API endpoint via streaming.
It works in conjunction with `AssistantResponse` in the backend.

<FrameworkTabs>
  <Tab>
To use `experimental_useAssistant` in React projects, you can import it from the `ai/react` subpath. 
Here's an example demonstrating the use of `experimental_useAssistant` in a chat interface:

```tsx filename="app/assistant.tsx"
'use client';

import {
  Message,
  // import as useAssistant:
  experimental_useAssistant as useAssistant,
} from 'ai/react';

const roleToColorMap: Record<Message['role'], string> = {
  system: 'red',
  user: 'black',
  function: 'blue',
  assistant: 'green',
  data: 'orange',
};

export default function Chat() {
  const { status, messages, input, submitMessage, handleInputChange } =
    useAssistant({ api: '/api/assistant' });

  return (
    <div className="flex flex-col w-full max-w-md py-24 mx-auto stretch">
      {messages.map((m: Message) => (
        <div
          key={m.id}
          className="whitespace-pre-wrap"
          style={{ color: roleToColorMap[m.role] }}
        >
          <strong>{`${m.role}: `}</strong>
          {m.role !== 'data' && m.content}
          {m.role === 'data' && (
            <>
              {/* here you would provide a custom display for your app-specific data:*/}
              {(m.data as any).description}
              <br />
              <pre className={'bg-gray-200'}>
                {JSON.stringify(m.data, null, 2)}
              </pre>
            </>
          )}
          <br />
          <br />
        </div>
      ))}

      {status === 'in_progress' && (
        <div className="h-8 w-full max-w-md p-2 mb-8 bg-gray-300 dark:bg-gray-600 rounded-lg animate-pulse" />
      )}

      <form onSubmit={submitMessage}>
        <input
          disabled={status !== 'awaiting_message'}
          className="fixed bottom-0 w-full max-w-md p-2 mb-8 border border-gray-300 rounded shadow-xl"
          value={input}
          placeholder="What is the temperature in the living room?"
          onChange={handleInputChange}
        />
      </form>
    </div>
  );
}
```

### `UseAssistantOptions`

<OptionTable
  options={[
    [
      'api',
      'string',
      'The API endpoint that accepts a `{ threadId: string | null; message: string; }` object and returns an `AssistantResponse` stream. ' +
        'The threadId refers to an existing thread with messages (or is `null` to create a new thread). ' +
        'The message is the next message that should be appended to the thread and sent to the assistant.',
    ],
    [
      'threadId',
      'string | undefined',
      'An optional string that represents the ID of an existing thread. If not provided, a new thread will be created.',
    ],
    [
      'credentials',
      '"omit" | "same-origin" | "include"',
      'An optional literal that sets the mode of credentials to be used on the request. Defaults to "same-origin".',
    ],
    [
      'headers',
      'Record<string, string> | Headers',
      'An optional object of headers to be passed to the API endpoint.',
    ],
    [
      'body',
      'any',
      'An optional, additional body object to be passed to the API endpoint.',
    ],
    [
      'onError',
      '(err: Error) => void',
      'An optional callback that will be called when the assistant encounters an error',
    ],
  ]}
/>

### `UseAssistantHelpers`

The `experimental_useAssistant` hook returns an object with several helper methods and variables to manage the assistant state in the UI:

<OptionTable
  options={[
    ['messages', 'Message[]', 'The current array of chat messages.'],
    ['threadId', 'string | undefined', 'The current thread ID.'],
    ['input', 'string', 'The current value of the input field.'],
    [
      'setInput',
      'React.Dispatch<React.SetStateAction<string>>',
      'Function to update the `input` value.',
    ],
    [
      'handleInputChange',
      '(e: any) => void',
      "Handler for the `onChange` event of the input field to control the input's value.",
    ],
    [
      'submitMessage',
      '(event?: React.FormEvent<HTMLFormElement>) => void',
      'Form submission handler that automatically resets the input field and appends a user message.',
    ],
    [
      'status',
      '"awaiting_message" | "in_progress"',
      'The current status of the assistant. This can be used to show a loading indicator.',
    ],
    [
      'error',
      'undefined | Error',
      'The error thrown during the assistant message processing, if any.',
    ],
  ]}
/>

</Tab>
</FrameworkTabs>
